<template>
  <div class="app-container">

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <el-form ref="itemInfo" :model="itemInfo" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="itemName">
          <el-col :span="12" >
            <el-input v-model="itemInfo.itemName" maxlength="30" show-word-limit/>
          </el-col>
        </el-form-item>
        <el-form-item label="商品简介" prop="simpleDesc">
          <el-col :span="12" >
            <el-input v-model="itemInfo.simpleDesc" type="textarea" maxlength="100" show-word-limit :autosize="{ minRows: 1, maxRows: 2}" placeholder="请输入内容"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="商品类目" required>
          <el-col :span="6" >
            <el-cascader v-model="categoryIds" clearable :options="categoryOptions" @change="handleCategoryChange"
              :props="{value: 'key', label: 'value', children: 'children', expandTrigger: 'hover'}" />
          </el-col>
        </el-form-item>
        <el-form-item label="主图" required>
          <el-col :span="6" >
            <el-upload
              :action="uploadFile"
              :headers="headers"
              class="item-image-uploader"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :on-success="handlePrimaryPicSuccess"
              accept=".jpg,.jpeg,.png,.gif">
              <img v-if="itemInfo.primaryPic" :src="itemInfo.primaryPic" class="item-image">
              <i v-else class="el-icon-plus item-image-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-form-item>
        <el-form-item label="轮播图" required>
          <el-upload
            :action="uploadFile"
            :headers="headers"
            list-type="picture-card"
            :limit="5"
            :before-upload="beforeImageUpload"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-success="handleSwiperPicSuccess"
            :file-list="swiperPicList"
            accept=".jpg,.jpeg,.png,.gif">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品详情" prop="dictLabel">
          <el-col :span="12" >
            <editor v-model="itemInfo.detail" />
          </el-col>
        </el-form-item>
        <div style="height: 50px"/>
        <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="itemInfo.sort" controls-position="right" :min="0" />
      </el-form-item>
        <el-form-item label="状态" prop="itemStatus">
          <el-radio-group v-model="itemInfo.itemStatus">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="12" >
            <el-input v-model="itemInfo.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品规格</span>
        <el-button type="text" style="float: right; padding: 3px 0" @click="handleSpecShow(null, -1)">添加</el-button>
      </div>
      <div style="margin-top: 20px" v-for="(spec, index) in itemInfo.specList">
        <div class="spec-header">
          <el-row>
            <el-col :span="6">
              <span>{{spec.name}}</span>
              <el-button type="primary" size="mini" class="button-new-tag" @click="handleSpecShow(spec, index)">修改</el-button>
              <el-input
                class="input-new-tag"
                v-if="addOptionVisible === spec.name"
                v-model="addOptionValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="addSpecOption(spec)"
                @blur="addSpecOption(spec)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showAddOption(spec)">+ 规格选项</el-button>
            </el-col>
          </el-row>
        </div>
        <div style="margin-top: 10px">
          <draggable v-model="spec.options">
            <el-tag v-for="specOption in spec.options" closable @close="deleteSpecOption(spec, specOption)" >{{specOption.option}}</el-tag>
          </draggable>
        </div>
        <el-dialog :visible.sync="specOpen" title="添加规格选项">
          <el-form
            ref="specForm"
            :model="specForm"
            status-icon
            label-position="left"
            label-width="100px"
            style="width: 400px; margin-left:50px;"
          >
            <el-form-item label="规格名称" prop="name">
              <el-input v-model="specForm.name" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="specForm.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-form>
          <el-table :data="specForm.options">
            <el-table-column type="index" label="排序" width="100"></el-table-column>
            <el-table-column prop="option" label="选项" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.option" placeholder="选项"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" @click="addSpecOptionColumn">添加数据</el-button>
          <div slot="footer" class="dialog-footer">
            <el-button @click="specOpen = false">取消</el-button>
            <el-button type="primary" @click="addSpec">确定</el-button>
          </div>
        </el-dialog>
      </div>

      <el-divider></el-divider>
      <div class="clearfix" style="margin-bottom: 10px;">
        <span>SKU列表</span>
        <el-button type="primary" size="mini" style="margin: 0 10px; padding: 5px 5px" @click="handleSkuShow(null, -1)">添加</el-button>
      </div>
      <el-table :data="itemInfo.skuList">
        <el-table-column prop="itemNo" label="货号" />
        <el-table-column prop="retailPrice" label="销售价" />
        <el-table-column prop="activityPrice" label="活动价" />
        <el-table-column prop="stockNum" label="库存" />
        <el-table-column prop="skuStatus" label="上下架" />
        <el-table-column v-for="spec in itemInfo.specList" prop="specNames" :label="spec.name" :formatter="specFormatter" />
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleSkuShow(scope.row, scope.$index)">
              <i class="el-icon-edit" aria-hidden="true"></i>
            </el-button>
            <el-button type="text" size="medium" @click="deleteSku(scope.row, scope.$index)">
              <i class="el-icon-delete" aria-hidden="true"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="skuOpen" title="添加SKU">
        <el-form
          ref="skuForm"
          :model="skuForm"
          :rules="skuFormRules"
          status-icon
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="货号" prop="itemNo" >
            <el-input v-model="skuForm.itemNo" />
          </el-form-item>
          <el-form-item label="销售价" prop="retailPrice" >
            <el-input v-model="skuForm.retailPrice" placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="活动价" prop="activityPrice" placeholder="0.00" >
            <el-input v-model="skuForm.activityPrice" >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="库存" prop="stockNum" >
            <el-input v-model="skuForm.stockNum" />
          </el-form-item>
          <el-form-item label="上下架" prop="skuStatus" >
            <el-radio-group v-model="skuForm.skuStatus">
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="2">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-for="spec in skuForm.specList" :prop="spec.name" :label="spec.name" >
            <el-radio-group @change="handleOptionCheck" v-model="spec.choose">
              <el-radio v-for="(optionOption, j) in spec.options" :key="j" :label="j">{{optionOption.option}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSkuForm('skuForm')">取消</el-button>
            <el-button type="primary" @click="submitSkuForm('skuForm')">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品属性</span>
        <el-button type="text" style="float: right; padding: 3px 0" @click="handleAttributeShow(null, -1)">添加</el-button>
      </div>
      <el-table :data="itemInfo.attrList">
        <el-table-column property="attrName" label="属性名称" />
        <el-table-column property="attrValue" label="属性值" />
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleAttributeShow(scope.row, scope.$index)" >
              <i class="el-icon-edit" aria-hidden="true"></i>
            </el-button>
            <el-button type="text" size="medium" @click="handleAttributeDelete(scope.row, scope.$index)">
              <i class="el-icon-delete" aria-hidden="true"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="attributeOpen" title="添加商品属性">
        <el-form
          ref="attributeForm"
          :model="attributeForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="属性名称" prop="attrName">
            <el-input v-model="attributeForm.attrName" />
          </el-form-item>
          <el-form-item label="属性值" prop="attrValue">
            <el-input v-model="attributeForm.attrValue" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeOpen = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button size="medium">取消</el-button>
      <el-button size="medium" type="primary" @click="handleSaveItem" >确定</el-button>
    </div>
  </div>
</template>

<script>
  import { getItem, addItem, updateItem } from "@/api/item/item"
  import { getToken } from '@/utils/auth'
  import Editor from '@/components/Editor'
  import draggable from 'vuedraggable'

  function sortSpecOption(a, b) {
    return a.sort - b.sort;
  }

  export default {
    name: "ItemInfo",
    components: {
      Editor,
      draggable
    },
    data() {
      var validateSpec = (rule, value, callback) => {
        let choose;
        let specName;
        this.skuForm.specList.forEach(spec => {
          if (spec.name === rule.field) {
            choose = spec.choose;
            specName = spec.name;
            return;
          }
        });
        if (choose === undefined || choose === null || choose === -1) {
          callback(new Error('请选择规格['+ specName +']选项'));
        } else {
          callback();
        }
      };
      return {
        uploadFile: process.env.VUE_APP_BASE_API + "/file/upload?path=items",
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        // 遮罩层
        loading: true,
        itemInfo: {
          // 基础信息
          itemId: undefined,
          itemName: undefined,
          simpleDesc: undefined,
          primaryPic: undefined,
          categoryId: undefined,
          swiperPics: [],
          detail: '',
          sort: undefined,
          itemStatus: 0,
          remark: '',
          // sku
          skuList: [],
          // 商品规格
          specList: [],
          // 商品属性
          attrList: []
        },
        swiperPicList: [],
        specOpen: false,
        specForm: {
          index: undefined,
          name: undefined,
          sort: 0,
          options: []
        },
        addOptionVisible: false,
        addOptionValue: '',
        skuOpen: false,
        skuForm: {},
        skuFormRules: {
          itemNo: [
            { required: true, message: '请输入sku货号', trigger: 'blur' }
          ],
          retailPrice: [
            { required: true, message: '请输入sku价格', trigger: 'blur' }
          ],
          stockNum: [
            { required: true, message: '请输入sku库存数量', trigger: 'blur' }
          ],
          spec: [
            { required: true, validator: validateSpec, trigger: 'change' }
          ]
        },
        attributeOpen: false,
        attributeForm: { attrId: undefined, attrName: '', attrValue: '' },
        categoryOptions: [],
        categoryIds: [],
        rules: {
          itemName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          simpleDesc: [
            { required: true, message: '请输入商品简介', trigger: 'blur' }
          ]
        }
      };
    },
    created() {
      const itemId = this.$route.query && this.$route.query.itemId;
      if (itemId) {
        this.getItem(itemId);
      } else {
        this.itemInfo.specList.push({name: '规格', options: []});
      }
      this.getOptions("item-category").then(response => {
        this.categoryOptions = response.data.options;
      });
    },
    methods: {
      /** 查询字典类型详细 */
      getItem(itemId) {
        getItem(itemId).then(response => {
          this.itemInfo = response.data;
          this.itemInfo.swiperPics.forEach(pic => {
            let obj = new Object();
            obj.url = pic;
            this.swiperPicList.push(obj);
          })
          this.categoryIds = ['' + this.itemInfo.category.pid, '' + this.itemInfo.category.id];
          if (!this.itemInfo.specList || this.itemInfo.specList.length == 0) {
            this.itemInfo.specList.push({name: '规格', options: []});
          }
        });
      },
      handlePrimaryPicSuccess(res, file) {
        this.itemInfo.primaryPic = res.data.url;
      },
      handleSwiperPicSuccess(res, file, fileList) {
        let obj = new Object();
        obj.url = res.data.url;
        this.swiperPicList.push(obj);
        this.itemInfo.swiperPics.push(res.data.url);
      },
      beforeImageUpload(file) {
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          this.$message.error('上传头像图片大小不能超过 1MB!');
        }
        return isLt1M;
      },
      handleRemove(file, fileList) {
        let url = file.url;
        for (let i = 0; i < this.itemInfo.swiperPics.length; i++) {
          if (this.itemInfo.swiperPics[i] === url) {
            this.itemInfo.swiperPics.splice(i, 1);
            this.swiperPicList.splice(i, 1);
            break;
          }
        }
      },
      handleExceed(files, fileList) {
        this.$message({
          type: 'error',
          message: '上传文件个数超出限制!最多上传5张图片!'
        })
      },
      handleCategoryChange(value) {
        this.itemInfo.categoryId = value[value.length - 1];
      },
      // SKU
      handleSkuShow(sku, index) {
        let specList = [];
        for (let spec of this.itemInfo.specList) {
          specList.push({
            name: spec.name,
            options: spec.options,
            choose: undefined
          });
          // 添加rules
          this.skuFormRules[spec.name] = this.skuFormRules['spec'];
        }

        if (index != -1) {
          this.skuForm = {
            index: index,
            itemNo: sku.itemNo,
            retailPrice: sku.retailPrice,
            activityPrice: sku.activityPrice,
            stockNum: sku.stockNum,
            skuStatus: sku.skuStatus
          };
          let map = {}
          sku.specOptions.forEach(row => {
            map[row.spec] = row.option
          })
          specList.forEach(spec => {
            for (let i = 0; i < spec.options.length; i++) {
              let specOption = spec.options[i];
              if (specOption.option == map[spec.name]) {
                spec.choose = i;
                break;
              }
            }
          })
        } else {
          this.skuForm = {
            index: index,
            retailPrice: undefined,
            activityPrice: undefined,
            stockNum: undefined,
            skuStatus: 1
          };
        }
        this.skuForm.specList = specList;
        this.skuOpen = true;
      },
      deleteSku(sku, index) {
        this.itemInfo.skuList.splice(index, 1);
      },
      handleOptionCheck() {
        this.$forceUpdate();
      },
      submitSkuForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let specOptions = [];
            this.skuForm.specList.forEach(spec => {
              specOptions.push({spec: spec.name, option: spec.options[spec.choose].option});
            })
            // 新增SKU
            const index = this.skuForm.index;
            if (index == -1) {
              this.itemInfo.skuList.push({
                itemNo: this.skuForm.itemNo,
                retailPrice: this.skuForm.retailPrice,
                activityPrice: this.skuForm.retailPrice,
                skuStatus: this.skuForm.skuStatus,
                stockNum: this.skuForm.stockNum,
                specOptions: specOptions
              })
            } else {
              let sku = this.itemInfo.skuList[index];
              sku.itemNo = this.skuForm.itemNo;
              sku.retailPrice = this.skuForm.retailPrice;
              sku.activityPrice = this.skuForm.activityPrice;
              sku.skuStatus = this.skuForm.skuStatus;
              sku.stockNum = this.skuForm.stockNum;
              sku.specOptions = specOptions;
            }
            this.skuOpen = false;
          } else {
            return false;
          }
        });
      },
      resetSkuForm(formName) {
        this.skuOpen = false;
        this.$refs[formName].resetFields();
      },
      // 规格
      handleSpecShow(spec, index) {
        if (index != -1) {
          this.specForm = {
            index: index,
            name: spec.name,
            sort: index + 1,
            options: spec.options
          }
        } else {
          if (this.itemInfo.specList && this.itemInfo.specList.length >= 3) {
            this.$message({
              type: 'error',
              message: '规格最多3个!'
            })
            return;
          }
          this.specForm = {
            index: index,
            name: '',
            sort: '',
            options: []
          }
        }
        this.specOpen = true;
      },
      showAddOption(spec) {
        this.addOptionVisible = spec.name;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      addSpecOption(spec) {
        let inputValue = this.addOptionValue;
        if (inputValue) {
          spec.options.push({option: inputValue})
        }
        this.addOptionVisible = '';
        this.addOptionValue = '';
      },
      deleteSpecOption(spec, specOption) {
        spec.options.splice(spec.options.indexOf(specOption), 1);
      },
      addSpecOptionColumn() {
        this.specForm.options.push({})
      },
      addSpec() {
        let options = [];
        for (let specOption of this.specForm.options) {
          if (specOption.option && specOption.option != '') {
            options.push(specOption);
          }
        }
        // 新增规格
        const index = this.specForm.index;
        if (index == -1) {
          this.itemInfo.specList.push({
            id: undefined,
            name: this.specForm.name,
            sort: this.specForm.sort,
            options: options
          })
        } else {
          let spec = this.itemInfo.specList[index];
          spec.name = this.specForm.name;
          spec.sort = this.specForm.sort;
          spec.options = options;
        }
        this.itemInfo.specList.sort(sortSpecOption);
        this.specOpen = false;
      },
      specFormatter(row, column) {
        for (let specOption of row.specOptions) {
          if (specOption.spec === column.label) {
            return specOption.option;
          }
        }
        return "";
      },
      // 属性
      handleAttributeShow(row, index) {
        this.attributeForm = {...row, index: index};
        this.attributeOpen = true;
      },
      handleAttributeAdd() {
        const index = this.attributeForm.index;
        if (index == -1) {
          this.itemInfo.attrList.push({
            attrId: undefined,
            attrName: this.attributeForm.attrName,
            attrValue: this.attributeForm.attrValue
          });
        } else {
          let attr = this.itemInfo.attrList[index];
          if (attr.attrId === this.attributeForm.attrId) {
            attr.attrName = this.attributeForm.attrName;
            attr.attrValue = this.attributeForm.attrValue;
          }
        }
        this.attributeOpen = false;
      },
      handleAttributeDelete(row, index) {
        this.itemInfo.attrList.splice(index, 1);
      },
      // 保存商品
      handleSaveItem() {
        this.$refs['itemInfo'].validate((valid) => {
          if (valid) {
            const categoryId = this.categoryIds[1];
            if (this.itemInfo.itemId) {
              updateItem({...this.itemInfo, categoryId: categoryId}).then(res => {
                const itemId = res.data.itemId;
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({path: '/item/item-info', query: {itemId: itemId}});
              })
            } else {
              addItem({...this.itemInfo, categoryId: categoryId}).then(res => {
                const itemId = res.data.itemId;
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({path: '/item/item-info', query: {itemId: itemId}});
              })
            }
          }
        });
      }
    }
  }
</script>

<style>
  .el-card {
    margin-bottom: 10px;
  }

  .item-image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .item-image-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .item-image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .item-image {
    width: 148px;
    height: 148px;
    display: block;
  }
  .op-container {
    display: flex;
    justify-content: center;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
